package com.yao.spider.yiyao;



import com.yao.spider.core.util.MyBatiesUtils;
import com.yao.spider.yiyao.bean.DongFMBean;
import com.yao.spider.yiyao.bean.DongFMErrorBean;
import com.yao.spider.yiyao.bean.MedicineInfoStandard;
import com.yao.spider.yiyao.dao.*;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.ibatis.session.SqlSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class DongFRequest {
    public static SqlSession sqlSession = MyBatiesUtils.getSqlSession();

    public static void getDetailByName() {
        MedicineInfoStandardDao medicineInfoStandardDao = new MedicineInfoStandardDaoImpl();
        SqlSession sqlSession = MyBatiesUtils.getSqlSession();
        List<MedicineInfoStandard> medicineInfoStandardList = medicineInfoStandardDao.selectShiYzNullAll(sqlSession);
        for (MedicineInfoStandard medicineInfoStandard : medicineInfoStandardList) {
            final OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .headers(Headers.of(HttpUtil.buildDongFHeaderMap()))
                    .url("https://www.yaozs.com/data/sms.php?nomal_name=" + URLEncoder.encode(medicineInfoStandard.getMedicineName()) +"&approval_number=&indication=")
//                    .url("https://www.yaozs.com/data/sms.php?nomal_name=%E7%BB%B4%E7%94%9F%E7%B4%A0&approval_number=&indication=")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    if (response.code() == 403) {
                        System.out.println(response.code());
                        Thread.sleep(1000 * 60 * 10);
                    }
                    throw new IOException("Unexpected code " + response);
                } else {
                    String resPage = response.body().string();
                    Document parse = Jsoup.parse(resPage);
                    Elements list = parse.getElementsByClass("list");
                    if (list.size() > 0) {
                        Elements row_clearfix = list.get(0).getElementsByClass("row clearfix");
                        for (Element element : row_clearfix) {
                            Element elementA = element.firstElementChild();
                            String text = elementA.text();
                            if (text.equals(medicineInfoStandard.getMedicineName())) {
                                String attr = elementA.attributes().get("href");
                                String substring = attr.substring(4, attr.length() - 1);
                                DongFMBean bean = smDetail(Integer.valueOf(substring));
                                if (bean != null) {
                                    medicineInfoStandard.setAboutJb(bean.getAboutJb());
                                    medicineInfoStandard.setShiYz(bean.getShiYz());
                                    medicineInfoStandardDao.updateById(sqlSession, medicineInfoStandard);
                                    System.out.println(medicineInfoStandard);
                                    break;
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static DongFMBean smDetail(Integer i) {
        DongFMBeanDao fastMailDao = new DongFMBeanDaoImpl();
        DongFMErrorBeanDao errorBeanDao = new DongFMErrorBeanDaoImpl();


        System.out.println(i);
        DongFMBean exportExcelBean = null;
        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .headers(Headers.of(HttpUtil.buildDongFHeaderMap()))
                .url("https://www.yaozs.com/sms" + i + "/")
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                if (response.code() == 403) {
                    System.out.println(response.code());
                    Thread.sleep(1000*60*10);

                }
                throw new IOException("Unexpected code " + response);
            } else {
                String resPage = response.body().string();
                Document parse = Jsoup.parse(resPage);
                Elements detail = parse.getElementsByClass("content-right");
                Elements detailList = detail.select("div");
                exportExcelBean = new DongFMBean();
                exportExcelBean.setIndex(i);
                for (Element element : detailList) {
                    Elements name = element.select("label");
                    if (name.size() == 1 && "批准文号：".equals(name.get(0).text())) {
                        System.out.print(name.get(0).text());
                        Elements content = element.select("span");
                        System.out.println(content.get(0).text());
                        exportExcelBean.setApplyNo(content.get(0).text());
                    }
                    if (name.size() == 1 && "相关疾病：".equals(name.get(0).text())) {
                        System.out.print(name.get(0).text());
                        Elements content = element.select("span");
                        System.out.println(content.get(0).text());
                        exportExcelBean.setAboutJb(content.get(0).text());
                    }
                    if (name.size() == 1 && "适应症：".equals(name.get(0).text())) {
                        System.out.print(name.get(0).text());
                        Elements content = element.select("span");
                        System.out.println(content.get(0).text());
                        exportExcelBean.setShiYz(content.get(0).text());
                    }

                }
                if (exportExcelBean != null) {
                    fastMailDao.insert(exportExcelBean, sqlSession);
                    return exportExcelBean;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            DongFMErrorBean errorBean = new DongFMErrorBean();
            errorBean.setIndex(Integer.valueOf(i));
            errorBeanDao.insert(errorBean, sqlSession);
        }
        return null;
    }
    public static void main(String[] args) {
//        smDetail("");
        getDetailByName();

    }
//    　按国家规定，化学制剂等西药产品均需在其说明书或标签上注明“适应症”，中药产品（主要是成药）需在其说明书标签上注明“功能与主治”。

}
